package org.geektimes.projects.user.web.controller;

import org.apache.commons.lang.StringUtils;
import org.geektimes.context.ComponentContext;
import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.service.UserService;
import org.geektimes.util.MD5;
import org.geektimes.web.mvc.controller.PageController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.concurrent.atomic.AtomicLong;

@Path("/user")
public class DoRegisterController implements PageController {

    private static AtomicLong idCreator = new AtomicLong(6);

//    @Resource(name = "bean/UserService")
//    private UserService service;

    @POST
    @Path("/register")
    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Throwable {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String phoneNumber = request.getParameter("phoneNumber");

        User user = new User();
        //自增id
//        user.setId(idCreator.incrementAndGet());

        if (StringUtils.isEmpty(name)) {
            request.setAttribute("nameError","用户名为空!");
            return "register.jsp";
        }

        if (StringUtils.isEmpty(password)) {
            request.setAttribute("passwordError","密码为空!");
            return "register.jsp";
        }

        if (StringUtils.isEmpty(email)) {
            request.setAttribute("emailError","邮箱为空!");
            return "register.jsp";
        }

        if (StringUtils.isEmpty(phoneNumber)) {
            request.setAttribute("phoneNumberError","电话号码为空!");
            return "register.jsp";
        }

        user.setName(name);
        user.setPassword(MD5.md5(password));
        user.setEmail(email);
        user.setPhoneNumber(phoneNumber);

        UserService service = ComponentContext.getInstance().getComponent("bean/UserService");
        service.register(user);

        return "index.jsp";
    }
}
